package com.treeroot.uploadservice.controller;

import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.treeroot.commonutils.result.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * @Description:
 * @Author:treeRoot
 * @Email:553503639@qq.com
 * @Date: Create in 13:51 / 2022/5/5
 */
@Api(description = "文件操作相关")
@RestController
@RequestMapping("/upload")
@Transactional
public class AvatarController {

    @Value("${yuan.file.root.path}")
    public String fileRootPath;

    @ApiOperation("文件上传")
    @PostMapping()
    public R upload(@RequestParam("file") MultipartFile file,
                    HttpServletRequest request) {
        String filePath = ""; // 文件保存的位置
        String urlPath = "";// 文件web浏览路径

        Assert.isTrue(!file.isEmpty(), "文件为空");
        // 原始名 以 a.jpg为例
        String originalFilename = file.getOriginalFilename();

        // 获取后缀并拼接'/'用于分类,也可以用日期 例: suffix = "jpg/"
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1) + "/";
        System.out.println(suffix);
        // 加上时间戳生成新的文件名,防止重复 newFileName = "1595511980146a.jpg"
        String newFileName = System.currentTimeMillis() + originalFilename;
        System.out.println(1+newFileName);

        filePath = fileRootPath + suffix + newFileName;
        System.out.println(filePath);

        try {

            File file1 = new File(filePath);
            if (!file1.exists())
                file1.mkdirs(); // 要是目录不存在,创建一个

            file.transferTo(file1);              // 保存起来

            urlPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/archive/" + suffix + newFileName;

        } catch (Exception e) {

            e.printStackTrace();
        }
        return R.ok().data("url", urlPath);
    }
}
